// pages/cart/cart.js
var http = require('../../API/http')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    list: [], //购物车列表
    allCheck: false, //全选按钮
    sum: '', //选中商品价格：件数*价格
    address: {}, //用户收货地址
    paddress: "", //地址拼接
    num: '', //选中商品数量
    flag: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },

  // 复选框状态
  onChange(e) {
    let id = e.currentTarget.dataset.id;
    this.data.list.forEach((item, i) => {
      if (item.id == id) {
        item.flag = !item.flag
        let flag = this.data.list.every(item => item.flag)
        this.setData({
          list: this.data.list,
          allCheck: flag
        })
        this.getsum()
        wx.setStorageSync('cartList', this.data.list)
      }
    })
  },
  // 全选按钮
  eckAll(e) {
    this.setData({
      allCheck: !this.data.allCheck
    })
    this.data.list.forEach(item => {
      item.flag = this.data.allCheck;
    })
    this.setData({
      list: this.data.list
    })
    this.getsum()
    wx.setStorageSync('cartList', this.data.list)
  },
  // 步进器
  jj(e) {
    let id = e.currentTarget.dataset.id;
    this.data.list.forEach((item, i) => {
      if (item.id == id) {
        item.num = e.detail;
        wx.setStorageSync('cartList', this.data.list)
      }
    })
    this.getsum()
  },
  // 计算选中的商品总价格
  getsum() {
    let sum = 0;
    let num = 0;
    this.data.list.forEach(item => {
      if (item.flag) {
        sum += item.num * item.price
        num += item.num
      }
    })
    this.setData({
      sum,
      num,
    })
  },
  // 获取用户收货地址
  address() {
    if(!wx.getStorageSync('token')){
      
      wx.switchTab({
        url: '/pages/my/my',
      })
      wx.showToast({
        title: '请先登录',
        icon:'error'
      })
      return false
    }
    // 请求用户的收货地址
    let flag = null
    wx.getSetting({
      success:res=>{
        console.log(res);
        if(res.authSetting['scope.address']){
          console.log('授权没有过期');
          wx.chooseAddress({
            // 点击确定调用
            success: (res) => {
              wx.setStorageSync('address', res)
              this.setData({
                address: wx.getStorageSync('address')
              })
            },
            // 点击取消调用
            fail: (err) => {
              console.log(err);
            }
          })
        }
      }
    })
    
  },
  // 点击商品图片、名称跳转到详情页
  xq(e){
    wx.navigateTo({
      url: '/pages/detail/detail?id='+e.currentTarget.dataset.id,
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.setData({
      flag: JSON.stringify(this.data.address) === '{}'
    })
    if (wx.getStorageSync('cartList')) {
      let flag = null
      flag = wx.getStorageSync('cartList').every(item => item.flag)
      this.setData({
        list: wx.getStorageSync('cartList') || [],
        allCheck: flag,
        address: wx.getStorageSync('address') || {}
      })
    }
    if (JSON.stringify(this.data.address) !== '{}') {
      let obj = this.data.address;
      let str = obj.provinceName + obj.cityName + obj.countyName + obj.detailInfo
      this.setData({
        paddress: str
      })
    }
    if(!wx.getStorageSync('token')){
      this.setData({
        list:[]
      })
    }
    this.getsum()
  },

  // 跳转结算
  tojs() {
    // 选中任意一个或多个商品点击结算进行跳转
    if (this.data.num > 0 && this.data.paddress) {
      let arr=[]
      let obj={}
      this.data.list.forEach(item => {
        if (item.flag) {
          obj = {
            order_price: this.data.sum,
            consignee_addr: this.data.paddress,
            goods: [{
              goods_id: item.id,
              goods_number: item.num,
              goods_price: item.price
            }]
          }
          arr.push(item)
        }
      })
      wx.navigateTo({
        url: `/pages/payment/payment?cartInfo=${JSON.stringify(obj)}&address=${JSON.stringify(this.data.address)}&cartList=${JSON.stringify(arr)}`,
      })
    } 
    else if(!wx.getStorageSync('token')){
      wx.switchTab({
        url: '/pages/my/my',
      })
      wx.showToast({
        title: '请先登录',
        icon:'error'
      })
    }
    else if (!this.data.paddress) {
      wx.showToast({
        title: '请选择收货地址',
        icon: "error"
      })
    }


  },



  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})